#!/bin/bash
set -e

source_files() {
  script/build files | grep -vE '^\./(coverage|fixtures|version)/'
}

prepare() {
  local changed_files="$(source_files | xargs git diff --name-only --)"
  if [ -n "$changed_files" ]; then
    echo "Aborted: please commit the following files before continuing" >&2
    cat <<<"$changed_files" >&2
    exit 1
  fi

  local n=0
  for f in $(source_files); do
    go tool cover -mode=set -var="LiveCoverage$((++n))" "$f" > "$f"~
    sed -E '
      /^package /a\
      import "github.com/github/hub/v2/coverage"
      s/(LiveCoverage[0-9]+)\.Count\[([0-9]+)\][^;]+/coverage.Record(\1, \2)/g
    ' < "$f"~ > "$f"
    rm "$f"~
  done

  rm -rf "$HUB_COVERAGE"
  mkdir -p "${HUB_COVERAGE%/*}"
}

generate() {
  source_files | xargs git checkout --

  echo 'mode: count' > "$HUB_COVERAGE"~
  sed -E 's!^.+/(github.com/github/hub/v2/)!\1!' "$HUB_COVERAGE" | awk '
    { a[substr($0, 0, length()-2)] += $(NF) }
    END { for (k in a) print k, a[k] }
  ' >> "$HUB_COVERAGE"~

  go tool cover -func="$HUB_COVERAGE"~ > "${HUB_COVERAGE%.out}.func"
  if [ -z "$CI" ]; then
    go tool cover -html="$HUB_COVERAGE"~ -o "${HUB_COVERAGE%.out}.html"
  fi

  awk '/^total:/ { print $(NF) }' "${HUB_COVERAGE%.out}.func"
}

summarize() {
  local total_coverage
  local min_coverage="${1?}"
  total_coverage="$(generate)"
  echo "Code coverage: $total_coverage"
  local result="$(bc <<<"${total_coverage%\%} < $min_coverage")"
  if [ "$result" -eq 1 ]; then
    echo "Error: coverage dropped below the minimum threshold of ${min_coverage}%!"
    if [ -n "$CI" ]; then
      html_result="${HUB_COVERAGE%.out}.html"
      html_result="${html_result#$PWD/}"
      printf 'Please run `script/test --coverage` locally and open `%s` to analyze the results.\n' "$html_result"
    fi
    return 1
  fi
}

cmd="${1?}"
shift 1

case "$cmd" in
  prepare | generate | summarize )
    "$cmd" "$@"
    ;;
  * )
    exit 1
    ;;
esac
